package com.pay.controller.wx;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.WebUtils;

import com.pay.beans.WxCustLoginStatusBean;
import com.pay.constants.WeixinConstants;
import com.pay.dubbo.wx.MenuInfoServiceFacade;
import com.pay.dubbo.wx.WxCustomerServiceFacade;
import com.pay.entity.wx.MenuInfo;
import com.pay.util.NeedOpenId;
import com.pay.util.RedisCustUtil;

/**
 * @Description: 微信授权获取openId（供外部调用）
 * @see: WxUserInfoController 此处填写需要参考的类
 * @version 2016年10月19日 上午10:11:43
 * @author shulin.feng
 */
@Controller
@RequestMapping("wx")
public class WxAuthorizeController {

	private static Logger logger = LoggerFactory.getLogger(WxAuthorizeController.class);

	@Resource
	private WxCustomerServiceFacade wxCustomerServiceFacade;
	@Resource
	private MenuInfoServiceFacade menuInfoServiceFacade;



	/**
	 * @Description 微信菜单跳转事件授权（需登录）
	 * @param request
	 * @return
	 * @see 需要参考的类或方法
	 */
	@RequestMapping(value = "menu/{menuno}")
	@NeedOpenId(needOpenId = true)
	public String menuAuth(HttpServletRequest request, @PathVariable("menuno") String menuno) {
		String openId = (String) WebUtils.getSessionAttribute(request, WeixinConstants.sessionOpenIdKey);
		List<WxCustLoginStatusBean> wxcustList = null;
		try {
			wxcustList = RedisCustUtil.getCustByOpenid(openId, true);
		} catch (Exception e) {
			logger.info("微信菜单跳转事件授权异常", e);
			return null;
		}
		String customerNo = "";
		if (wxcustList != null && wxcustList.size() != 0) {
			customerNo = wxcustList.get(0).getCustomerNo();
		} else {
			customerNo = (String) request.getAttribute("customerNo");
		}

		logger.info("WxAuthorizeController/menuAuth/menuno:{}", menuno);
		MenuInfo menuInfo = menuInfoServiceFacade.findMenuInfoByMenuNo(menuno);
		if (menuInfo == null) {
			return "/include/error";
		}
		String url = menuInfo.getMenuUrl();
		StringBuffer sb = new StringBuffer();
		sb.append(url);
		if (url.contains("?")) {
			sb.append("&");
		} else {
			sb.append("?");
		}
		sb.append("openId=");
		sb.append(openId);
		sb.append("&v=");
		sb.append(menuInfo.getMenuVersion());
		sb.append("&customerNo=");
		sb.append(customerNo);
		logger.info("菜单跳转地址：{}", sb.toString());
		return "redirect:" + sb.toString();
	}


}
